<?php

declare(strict_types=1);

namespace Modules\Member\Models;

use Catch\Base\CatchModel as Model;
use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Support\Facades\Redis;
use Laravel\Sanctum\HasApiTokens;

/**
 * @property $id
 * @property $email
 * @property $mobile
 * @property $password
 * @property $avatar
 * @property $username
 * @property $address_id
 * @property $from
 * @property $status
 * @property $token
 * @property $last_login_at
 * @property $creator_id
 * @property $created_at
 * @property $updated_at
 * @property $deleted_at
 */
class Members extends Model implements AuthenticatableContract
{
    use Authenticatable, HasApiTokens;

    protected $table = 'members';

    public $timestamps = true;


    protected $fillable = [
        'id',
        'mobile',
        'password',
        'avatar',
        'username',
        'token',
        'address_id',
        'from',
        'status',
        'last_login_at',
        'is_first_login',
        'creator_id',
        'created_at',
        'updated_at',
        'deleted_at',
        'open_id',
        'union_id',
        'gzh_open_id',
        'real_name',
        'price',
        'invite_code',
        'withdraw_account',
        'pid',
        'user_level',
        'withdraw_all',
        'longitude',
        'latitude',
        'v1_buy_status',
        'wechat',
        'agent_start_at',
        'agent_end_at',
        'agent_city_name',
        'city_agent_status'
    ];

    protected array $fields = ['id', 'mobile', 'password', 'avatar', 'username', 'user_level','from', 'status','is_first_login', 'last_login_at', 'created_at',
        'open_id', 'union_id','gzh_open_id','invite_code','pid','user_level' ,'withdraw_all' ,'longitude',
        'latitude','v1_buy_status','wechat', 'agent_start_at', 'agent_end_at','agent_city_name','city_agent_status'];

    protected $appends = ['team_count'];
    public array $searchable = [
        'username' => 'like',
        'email' => 'like',
        'mobile' => 'like',
        'open_id' => '=',
        'id' => '=',
        'user_level' => '=',
        'status' => '=',
        'v1_buy_status' => '=',
    ];

    /**
     * 加密密码
     */
    protected function password(): Attribute
    {
        return new Attribute(
            set: fn($value) => bcrypt($value),
        );
    }

    protected function getTeamCountAttribute(): int
    {

        if(isset($this->attributes['id'])){
            $team = Redis::hget($this->attributes['id'],'team');
            if(!empty($team)){
                $arr = explode(",",$team);
                return  count($arr);
            }else{
                return 0;
            }
        }else{
            return 0;
        }
    }
}
